package com.kma.ncpractice2013.dao;

import com.kma.ncpractice2013.model.Hotel;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * User: Viktor
 * Date: 12/9/13
 */
public class HotelDAO extends DAO<Hotel>
{
	@Override
	public void create(Hotel o)
	{
		String sql="INSERT INTO HOTELS(NAME, LATITUDE, LONGITUDE, CITY, LOCATION_DESCR, ADDRESS, HOTEL_ID, COUNTRY) VALUES(?,?,?,?,?,?,?,?)";
		jdbcTemplate.update(sql, o.getName(), o.getLatitude(), o.getLongitude(), o.getCity(), o.getDescription(), o.getAddress(), o.getHotelId(), o.getCountry());
	}

	@Override
	public void update(Hotel o)
	{
		String sql = "UPDATE HOTELS SET NAME = ?, LATITUDE = ?, LONGITUDE = ?, CITY = ?, LOCATION_DESCR = ?, ADDRESS = ?, HOTEL_ID=?, COUNTRY=? WHERE  ID = ?";
		jdbcTemplate.update(sql, o.getName(), o.getLatitude(), o.getLongitude(), o.getCity(), o.getDescription(), o.getAddress(), o.getHotelId(), o.getCountry(), o.getId());
	}

	@Override
	public Hotel getById(int id)
	{
		List<Hotel> hotelList;
		String sql = "SELECT * FROM HOTELS WHERE ID = ?";
		hotelList = jdbcTemplate.query(sql, new HotelRowMapper(), id);
		return (hotelList==null||hotelList.isEmpty())?null:hotelList.get(0);
	}
	public Hotel getByHotelId(int id)
	{
		List<Hotel> hotelList;
		String sql = "SELECT * FROM HOTELS WHERE HOTEL_ID = ?";
		hotelList = jdbcTemplate.query(sql, new HotelRowMapper(), id);
		return (hotelList==null||hotelList.isEmpty())?null:hotelList.get(0);
	}

	@Override
	public Collection<Hotel> getAll()
	{
		String sql = "SELECT * FROM HOTELS";
		return jdbcTemplate.query(sql, new HotelRowMapper());

	}

	@Override
	public void deleteById(int id)
	{
		String sql = "DELETE FROM HOTELS WHERE ID = ?";
		jdbcTemplate.update(sql,id);
	}
	private static final class HotelRowMapper implements ParameterizedRowMapper<Hotel>
	{
		public Hotel mapRow(ResultSet rs, int rowNum) throws SQLException
		{
			Hotel hotel = new Hotel();
			hotel.setCity(rs.getString("city"));
			hotel.setAddress(rs.getString("address"));
			hotel.setName(rs.getString("name"));
			hotel.setDescription(rs.getString("location_descr"));
			hotel.setId(rs.getInt("id"));
			hotel.setLatitude(rs.getDouble("latitude"));
			hotel.setLongitude(rs.getDouble("longitude"));
			hotel.setHotelId(rs.getInt("hotel_id"));
			hotel.setCountry(rs.getString("country"));
			return hotel;
		}
	}
}
